//
//  DetailAddressVC.m
//  sensen_ios
//
//  Created by mc on 16/2/26.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "DetailAddressVC.h"

#import "BoyeChooseCityView.h"

#import "AddressModel.h"


@interface DetailAddressVC ()<UITableViewDataSource,UITableViewDelegate,BoyeChooseCityViewDelegate,UITextFieldDelegate>{
    UITableView         *  _tableView;
    NSArray             *  _textArray;
    CityObject          * _cityObject;

}

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic,strong) BoyeChooseCityView     *  chooseCityView;
@end

@implementation DetailAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建导航栏左边返回按钮
    [self createLeftBarButtonItemWithImagename:nil];
   
    self.title = @"地址管理";
    
    if (self.isDefault) {
        self.title = @"修改默认地址";
    }else{
        [self createRightBarButtonItemWithImagename:@"个人中心-管理收货地址详_删除"];

    }
    
    
    
    self.view.backgroundColor = rgba(237, 238, 239, 1);
    _textArray = @[@"所在地区",@"详细地址",@"收货人姓名",@"手机号码",@"邮编"];
    
    self.dataArray = [NSMutableArray arrayWithArray:@[self.addressModel.pcaAddress, self.addressModel.detailinfo, self.addressModel.contactname,self.addressModel.mobile,self.addressModel.postal_code]];
        
    [self buildTableView];
    [self buildAddView];
    [self buildChooseCity];
    
    
    
    // Do any additional setup after loading the view.
}

- (void)createRightBarButtonItemWithImagename:(NSString *)imgname {
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 25)];
    [rightButton addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setImage:[UIImage imageNamed:imgname] forState:UIControlStateNormal];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}


-(void)buildTableView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT- 64 -SCREEN_WIDTH / 8) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.contentInset = UIEdgeInsetsZero;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = rgba(237, 238, 239, 1);
    [_tableView reloadData];
}


#pragma mark -- TableViewDelegate --

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isDefault) {
        return 5;
    }else{
        return 6;
    }
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row < 5 && indexPath.row > 0) {
        static    NSString  * identifier = @"cell";
        UITableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.contentView.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 50);
            [BoyeViewHandle defaultLineInView:cell.contentView];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        }
        
        
        
        //输入框
        UITextField  *textField = [[UITextField alloc] init];
        textField.font = FONT(14);
        textField.borderStyle = UITextBorderStyleNone;
        [cell addSubview:textField];
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(20);
            make.top.equalTo(cell).offset(5);
            make.size.mas_equalTo(CGSizeMake(200, 20));
        }];
        textField.tag = indexPath.row;
        textField.textColor = [UIColor darkGrayColor];
        
        UILabel * titleLable = [[UILabel alloc] init];
        [cell addSubview:titleLable];
        titleLable.textColor = [UIColor colorWithHexString:@"#969696"];
        titleLable.font = FONT(13);
        [titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(20);
            make.bottom.equalTo(cell).offset(-5);
            make.size.mas_equalTo(CGSizeMake(200, 15));
            
        }];
        titleLable.text = _textArray[indexPath.row];

        textField.text = self.dataArray[indexPath.row];
        
        textField.delegate = self;
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        return cell;

    }else if (indexPath.row == 5){
        
        static    NSString  * identifier = @"cell";
        UITableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.contentView.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 50);
            //线
            [BoyeViewHandle defaultLineInView:cell.contentView];
            
            
            

        }
        
        
        UILabel * label = [[UILabel alloc] init];
        label.frame = CGRectMake(20, 2, SCREEN_WIDTH - 20, 40);
        label.font = FONT(14);
        label.text = @"设为默认地址";
        label.textColor = [UIColor darkGrayColor];
        [cell.contentView addSubview:label];
        
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [cell.contentView addSubview:button];
        button.tag = 1000;
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(cell.contentView).offset(- 15);
            make.centerY.equalTo(cell.contentView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(15, 15));
            
        }];
        
        [button setBackgroundImage:[UIImage imageNamed:@"个人中心-管理收货地址详情1_07"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"个人中心-管理收货地址详情_07"] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        return cell;

    }
    
    
    else{
        
        static    NSString  * identifier = @"cell";
        UITableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.contentView.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 50);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
        }
        
        
               
        [BoyeViewHandle defaultLineInView:cell.contentView];
        UILabel * valueLable = [[UILabel alloc] init];
        [cell.contentView addSubview:valueLable];
        valueLable.font = FONT(14);
        valueLable.tag = 1001;
        valueLable.textColor = [UIColor darkGrayColor];
        [valueLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(20);
            make.top.equalTo(cell).offset(5);
            make.size.mas_equalTo(CGSizeMake(200, 20));
        }];

        
        UILabel * titleLable = [[UILabel alloc] init];
        [cell addSubview:titleLable];
        titleLable.textColor = [UIColor colorWithHexString:@"#969696"];
        titleLable.font = FONT(14);
        [titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(20);
            make.bottom.equalTo(cell).offset(-5);
            make.size.mas_equalTo(CGSizeMake(200, 15));
            
        }];
        titleLable.text = _textArray[indexPath.row];
        valueLable.text = _dataArray[0];
        //tap
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseProvineCity:)];
        [cell addGestureRecognizer:tap];
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    if (indexPath.row < 5 && indexPath.row > 0) {
        UITableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
        UITextField * textField = (UITextField *)[cell viewWithTag:indexPath.row];
        
        [textField  becomeFirstResponder];

    }
    
    else if (indexPath.row == 5){
        UITableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
        UIButton * button = (UIButton *)[cell.contentView viewWithTag:1000];
        button.selected = !button.selected;
    }
    
}


- (void)buttonAction:(UIButton *)button{
    button.selected = !button.selected;
}

// 导航栏右侧按钮事件
- (void)rightAction:(UIButton *)button {
    
    [self requestDeleteAddress];
}




#pragma mark --   添加地址  ---

-(void)buildAddView{
    // 创建退出登录按钮
    UIButton  * saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, _tableView.bottom, SCREEN_WIDTH, SCREEN_WIDTH / 8);
    [self.view addSubview:saveBtn];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setBackgroundColor:SS_NAVI_BLUE_COLOR];

}

//修改地址
- (void)requestSaveAddress{
    
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)self.addressModel.address_id] forKey:@"id"];

        [diction setObject:self.addressModel.provinceid forKey:@"proviceid"];
        [diction setObject:self.addressModel.cityid forKey:@"cityid"];
        [diction setObject:self.addressModel.areaid forKey:@"areaid"];
        [diction setObject:self.addressModel.province forKey:@"province"];
        [diction setObject:self.addressModel.city forKey:@"city"];
        [diction setObject:self.addressModel.area forKey:@"area"];

    
    [diction setObject:self.dataArray[1] forKey:@"detailinfo"];
    [diction setObject:self.dataArray[2] forKey:@"contactname"];
    [diction setObject:self.dataArray[3] forKey:@"mobile"];
    [diction setObject:self.dataArray[4] forKey:@"postal_code"];
    [SVProgressHUD showWithStatus:@"正在保存...."];
    
    [BoyeHttpClient post:@"BY_Address_update" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result){
        NSLog(@"修改地址  %@", result);
        [SVProgressHUD showSuccessWithStatus:@"保存成功" withDuration:1];
        [self performSelector:@selector(test) withObject:nil afterDelay:1.0];
        
//        dispatch_queue_t mainQueue = dispatch_get_main_queue();
//        dispatch_async(mainQueue, ^{
//            
//            
//            [self performSelector:@selector(test) withObject:nil afterDelay:2.0];
//
//        });

        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"失败，请重试"] withDuration:3];
    }];
    
}


- (void)test{
    [self.navigationController popViewControllerAnimated:YES];
}

//设为默认地址
-(void) requestSetDefaultAddress{
    
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)self.addressModel.address_id] forKey:@"id"];
    [BoyeHttpClient post:@"BY_Address_setDefaultAddress" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        
       [SVProgressHUD showSuccessWithStatus:@"设为默认地址" withDuration:1];
       [self performSelector:@selector(test) withObject:nil afterDelay:1.0];
      
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"失败，请重试"] withDuration:3];
    }];
}








//删除地址
- (void)requestDeleteAddress{
    
    
    
    [SVProgressHUD showWithStatus:@"正在删除...."];
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)self.addressModel.address_id] forKey:@"id"];
    
    [BoyeHttpClient post:@"BY_Address_delete" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        

         [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"删除失败，请重试"] withDuration:3];

       
    }];

}




#pragma mark --  打开城市选择 --
-(void)chooseProvineCity:(UIGestureRecognizer *)recognizer{
    [_chooseCityView open];
    [self.view endEditing:YES];
    
}


#pragma  mark --  键盘下去 --
-(void)downKeyBoark{
    DLog(@"保存按钮！");
    [self.view endEditing:YES];
    [_chooseCityView close];
}
// 创建城市选择器

-(void)buildChooseCity{
    
    _chooseCityView = [[BoyeChooseCityView alloc] initWithPicker];
    _chooseCityView.delegate = self;
    [self.view addSubview: _chooseCityView];
}

#pragma mark ---- BoyeChooseCityView -----
-(void)chooseCityView:(BoyeChooseCityView *)chooseCity cityObject:(CityObject *)cityObject{
    
    DLog(@" -- %@ -- %@ - %@ - ",cityObject.city,cityObject.area,cityObject.province);
    
    _cityObject = cityObject;
    
    UITableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    UILabel * city = (UILabel *)[cell.contentView viewWithTag:1001];
    city.text = cityObject.pcaAddress;
    [self.dataArray replaceObjectAtIndex:0 withObject:cityObject.pcaAddress];
    
    
    self.addressModel.area = cityObject.area;
    self.addressModel.areaid = cityObject.areaid;
    self.addressModel.city = cityObject.city;
    self.addressModel.cityid = cityObject.cityid;
    self.addressModel.province = cityObject.province;
    self.addressModel.provinceid = cityObject.provinceid;
    self.addressModel.country = @"1017";
    self.addressModel.pcaAddress = [NSString stringWithFormat:@"%@%@%@",cityObject.province,cityObject.city,cityObject.area];
    
    
    if (cityObject.cityid == nil || cityObject.cityid.length == 0) {
        self.addressModel.cityid = @"0";
    }
    
    if (cityObject.areaid == nil || cityObject.areaid.length == 0) {
        self.addressModel.areaid = @"0";
    }
    if (cityObject.city == nil || cityObject.city.length == 0) {
        self.addressModel.city = @"0";
    }
    
    if (cityObject.area == nil || cityObject.area.length == 0) {
        self.addressModel.area = @"0";
    }

    
    
}



#pragma  mark --- textFieldDelegate ---
// TODO: zk
-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    DLog(@" textfield   -*%@*-   ",textField.text);
    [self.dataArray  replaceObjectAtIndex:textField.tag withObject:textField.text];

    
    
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    [textField resignFirstResponder];
    [_chooseCityView close];
    
    return YES;
}




#pragma mark  --   删除  --
- (void)deleteAction:(UITapGestureRecognizer *)tap{
    [self downKeyBoark];
    NSLog(@"删除");
}

#pragma mark  --   保存  --
- (void)saveAction:(UIButton *)button{
    [self downKeyBoark];
    
    
    if ([self.dataArray[2]  isStringNull] ) {
        [SVProgressHUD showOnlyStatus:@"联系人为空" withDuration:1];
        return;
    }
    
    if ([self.dataArray[3]   isStringNull] ) {
        [SVProgressHUD showOnlyStatus:@"联系电话为空" withDuration:1];
        return;
    }
    
    if ([self.dataArray[0] isStringNull] ) {
        [SVProgressHUD showOnlyStatus:@"请选择省市区" withDuration:1];
        return;
    }
    
    if ([self.dataArray[1]  isStringNull] ) {
        [SVProgressHUD showOnlyStatus:@"详细地址为空" withDuration:1];
        return;
    }

    
    
    
    [self requestSaveAddress];
    
    UITableViewCell * cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
    UIButton * btn = (UIButton *)[cell.contentView viewWithTag:1000];
    if (!self.isDefault && btn.selected) {
        [self requestSetDefaultAddress];
    }

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
